package com.rybbaby.tss.platform.sysHandlePermissions.controller;

import com.rybbaby.tss.core.annotation.RequestLog;
import com.rybbaby.tss.core.annotation.Token;
import com.rybbaby.tss.core.annotation.validator.RegexpValidator;
import com.rybbaby.tss.core.annotation.validator.StringValidator;
import com.rybbaby.tss.core.bean.PageBean;
import com.rybbaby.tss.core.hqlsearch.HqlGenerateUtil;
import com.rybbaby.tss.core.utils.AjaxJsonResponse;
import com.rybbaby.tss.core.utils.PropertiesReadUtil;
import com.rybbaby.tss.core.utils.SequenceUtil;
import com.rybbaby.tss.core.utils.StringUtils;
import com.rybbaby.tss.core.web.controller.BaseController;
import com.rybbaby.tss.platform.initializer.HandlePermissionsInitializer;
import com.rybbaby.tss.platform.sysHandlePermissions.entity.SysHandlePermissions;
import com.rybbaby.tss.platform.sysHandlePermissions.service.ISysHandlePermissionsService;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author 谢进伟
 * @description 操作权限管理
 * @createDate 2016-11-23 下午11:02:13
 */
@Controller
@RequestMapping(value = "sysHandlePermissionsController")
public class SysHandlePermissionsController extends BaseController {

    @Autowired
    private ISysHandlePermissionsService sysHandlePermissionsService;

    /**
     * 获取操作权限列表
     *
     * @return
     * @throws IOException
     */
    @RequestLog(content = "获取操作权限列表", save = true)
    @RequestMapping(value = "sysHandlePermissionsList", method = RequestMethod.POST)
    public ModelAndView sysHandlePermissionsList(SysHandlePermissions entity, PageBean paramPageBean) {
        ModelAndView mav = new ModelAndView(PropertiesReadUtil.getStringProperty("sysHandlePermissionsListView"));
        try {
            Map<String, String[]> unLockMap = getParameterMap(request);
            DetachedCriteria dc = DetachedCriteria.forClass(SysHandlePermissions.class);
            HqlGenerateUtil.fillDetachedCriteria(dc, entity, unLockMap);
            PageBean pageBean = sysHandlePermissionsService.pageList(dc, paramPageBean.getPageNo(), paramPageBean.getPageSize());
            mav.addObject(super.SEARCH_MAP, unLockMap);
            mav.addObject(super.PAGE_BEAN, pageBean);
            mav.addObject("searchFormId", SEARCH_FORM);
            mav.addObject("actionUrl", request.getRequestURI());
            mav.addObject("pagingBar", pageBean.getPagingBar(SEARCH_FORM));
            mav.addObject("serializeNum", SequenceUtil.getUpperCaseUUID());
            String requestURI = StringUtils.substringBeforeLast(request.getRequestURI(), "/");
            mav.addObject("editUrl", requestURI + "/toEditView.do");
            mav.addObject("deleteUrl", requestURI + "/delete.do");
            mav.addObject("batchDeleteUrl", requestURI + "/batchDelete.do");
        } catch (Exception e) {
            throw e;
        }
        return mav;
    }

    /**
     * 转到编辑视图
     *
     * @param entity       接收编辑参数的临时对象
     * @param serializeNum 请求标识
     * @return
     */
    @RequestLog(content = "转到操作权限视图", save = true)
    @RequestMapping(value = "toEditView", method = RequestMethod.GET)
    public ModelAndView toEditView(SysHandlePermissions entity, @RequestParam(required = true) String serializeNum) {
        ModelAndView mav = new ModelAndView(PropertiesReadUtil.getStringProperty("sysHandlePermissionsEditView"));
        if (entity != null && entity.getId() != null) {
            SysHandlePermissions editEntity = this.sysHandlePermissionsService.get(entity.getId());
            mav.addObject("editEntity", editEntity);
            mav.addObject("editModel", "edit");
        } else {
            mav.addObject("editModel", "add");
        }
        // 管理员Id数据源
        List<Map<String, Object>> adminUserPermissionAllotId_datasources = this.sysHandlePermissionsService.adminUserPermissionAllotIdDatasource();
        mav.addObject("adminUserPermissionAllotId_datasources", adminUserPermissionAllotId_datasources);
        // 角色Id数据源
        List<Map<String, Object>> rolePermissionAllotId_datasources = this.sysHandlePermissionsService.rolePermissionAllotIdDatasource();
        mav.addObject("rolePermissionAllotId_datasources", rolePermissionAllotId_datasources);
        mav.addObject("serializeNum", serializeNum);
        mav.addObject("saveUrl", StringUtils.substringBeforeLast(request.getRequestURI(), "/") + "/saveOrUpdate.do");
        return mav;
    }

    /**
     * 保存编辑的对象
     *
     * @param entity 被编辑对象
     * @return
     */
    @ResponseBody
    @RequestLog(content = "保存操作权限对象", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "saveOrUpdate", method = RequestMethod.POST)
    public String saveOrUpdate(SysHandlePermissions entity) {
        AjaxJsonResponse ajr = new AjaxJsonResponse();
        try {
            String id = entity.getId();
            ajr.setResMsg("保存成功!");
            if (StringUtils.isNotBlank(id)) {
                SysHandlePermissions destEntity = this.sysHandlePermissionsService.get(id);
                BeanUtils.copyProperties(entity, destEntity, "createTime", "createUserId");
                // 修改所有副本
                List<SysHandlePermissions> cloneSHPList = this.sysHandlePermissionsService.findByProperty("defaultHandlePermissionId", destEntity.getId());
                for (SysHandlePermissions cloneSHP : cloneSHPList) {
                    BeanUtils.copyProperties(entity, cloneSHP, "id", "defaultHandlePermissionId", "adminUserPermissionAllotId", "rolePermissionAllotId", "createTime", "createUserId", "version");
                }
                cloneSHPList.add(destEntity);
                this.sysHandlePermissionsService.batchUpdate(cloneSHPList);
                // 刷新缓存
                HandlePermissionsInitializer.reloadHandlePermission();
            } else {
                entity.setCreateTime(new java.sql.Timestamp(System.currentTimeMillis()));
                Object loginUserId_obj = getLoginUserId();
                entity.setCreateUserId(loginUserId_obj == null ? null : loginUserId_obj.toString());
                Serializable newId = this.sysHandlePermissionsService.save(entity);
                if (newId == null) {
                    ajr.setResCode(301);
                    ajr.setResMsg("保存失败!");
                } else {
                    // 刷新缓存
                    HandlePermissionsInitializer.reloadHandlePermission();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            ajr.setResCode(500);
            ajr.setResMsg("保存失败(" + e.getMessage() + ")!");
        }
        return ajr.jsonResponse(false);
    }

    /**
     * 此方法可以自动修复没有设置默认操作权限的历史操作权限
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "autoFindDefaultHandlePermissionId")
    public String autoFindDefaultHandlePermissionId() {
        List<String> sqls = new ArrayList<>();
        DetachedCriteria dc = DetachedCriteria.forClass(SysHandlePermissions.class);
        dc.add(Restrictions.or(Restrictions.and(Restrictions.isNull("adminUserPermissionAllotId"), Restrictions.isNotNull("rolePermissionAllotId")),
                Restrictions.and(Restrictions.isNotNull("adminUserPermissionAllotId"), Restrictions.isNull("rolePermissionAllotId"))));
        dc.add(Restrictions.isNull("defaultHandlePermissionId"));
        List<SysHandlePermissions> allCloneHandlePermissions = this.sysHandlePermissionsService.findByDetached(dc);
        for (SysHandlePermissions cloneHandlePermission : allCloneHandlePermissions) {
            DetachedCriteria dc1 = DetachedCriteria.forClass(SysHandlePermissions.class);
            dc1.add(Restrictions.eq("menuId", cloneHandlePermission.getMenuId()));
            dc1.add(Restrictions.eq("name", cloneHandlePermission.getName()));
            dc1.add(Restrictions.eq("code", cloneHandlePermission.getCode()));
            dc1.add(Restrictions.isNull("adminUserPermissionAllotId"));
            dc1.add(Restrictions.isNull("rolePermissionAllotId"));
            dc1.add(Restrictions.isNull("defaultHandlePermissionId"));
            List<SysHandlePermissions> byDetached = this.sysHandlePermissionsService.findByDetached(dc1);
            if (byDetached != null && !byDetached.isEmpty()) {
                if (byDetached.size() == 1) {
                    SysHandlePermissions sysHandlePermissions = byDetached.get(0);
                    String sql = "UPDATE sys_handle_permissions SET defaultHandlePermissionId='" + sysHandlePermissions.getId() + "' WHERE id='" + cloneHandlePermission.getId() + "'";
                    sqls.add(sql);
                } else if (byDetached.size() > 1) {
                    System.out.println("多个满足条件的默认操作权限");
                } else {
                    System.out.println("未找到默认操作权限");
                }
            }
        }
        boolean result = this.sysHandlePermissionsService.batchUpdate(StringUtils.join(sqls, "#####").split("#####"));
        AjaxJsonResponse ajr = new AjaxJsonResponse();
        if (!result) {
            ajr.setResMsg("自动更新失败!");
            ajr.setResCode(-1);
        }
        ajr.setData(sqls.toString());
        return ajr.jsonResponse(false);
    }

    /**
     * 删除指定id的对象
     *
     * @param id 需要被删除的对象id
     * @return
     */
    @ResponseBody
    @RequestLog(content = "删除属性", save = true)
    @RequestMapping(value = "delete", method = RequestMethod.GET)
    public String delete(@StringValidator(nullable = false) String id) {
        AjaxJsonResponse ajr = new AjaxJsonResponse();
        try {
            ajr.setResMsg("删除成功!");
            if (StringUtils.isNotBlank(id)) {
                SysHandlePermissions delteEntity = this.sysHandlePermissionsService.get(id);
                this.sysHandlePermissionsService.deleteEntityById(id);
                // 刷新缓存
                HandlePermissionsInitializer.reloadHandlePermission(delteEntity);
            } else {
                ajr.setResMsg("删除失败!");
                ajr.setResCode(302);
            }
        } catch (Exception e) {
            e.printStackTrace();
            ajr.setResCode(500);
            ajr.setResMsg("删除失败(" + e.getMessage() + ")!");
        }
        return ajr.jsonResponse(false);
    }

    /**
     * 批量删除指定id的对象
     *
     * @param ids 需要被删除的对象id组成的字符串
     * @return
     */
    @ResponseBody
    @RequestLog(content = "删除属性", save = true)
    @RequestMapping(value = "batchDelete", method = RequestMethod.GET)
    public String batchDelete(@RegexpValidator(nullable = false, regexp = "^(\\w+,?)+\\w+$") String ids) {
        AjaxJsonResponse ajr = new AjaxJsonResponse();
        try {
            ajr.setResMsg("删除成功!");
            if (StringUtils.isNotBlank(ids)) {
                DetachedCriteria dc = DetachedCriteria.forClass(SysHandlePermissions.class);
                String[] split = ids.split(",");
                dc.add(Restrictions.in("id", split));
                List<SysHandlePermissions> deleteEntitys = this.sysHandlePermissionsService.findByDetached(dc);
                boolean batchDelete = this.sysHandlePermissionsService.batchDelete(split);
                if (!batchDelete) {
                    ajr.setResMsg("删除失败!");
                    ajr.setResCode(302);
                } else {
                    // 刷新缓存
                    HandlePermissionsInitializer.reloadHandlePermission(deleteEntitys);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            ajr.setResCode(500);
            ajr.setResMsg("删除失败(" + e.getMessage() + ")!");
        }
        return ajr.jsonResponse(false);
    }
}
